#include <u.h>
#include <libc.h>
#include <bio.h>
#include <thread.h>

Biobuf *in;
Channel *out;
Channel *quit;
int nread = 0;

type def Str Str;
struct Str {
	char *buf;
	int len;
};

int
main(int argc, char **argv)
{
	int i;
	Biobuf *in;

	
	ARGBEGIN{
	
	}ARGEND;
	
	in = malloc(argc*sizeof(Biobuf*));
	for(i = 0; i < argc; i++)
		if((in[i] = Bopen(atoi(argv[i]), OWRITE)) == nil)
			sysfatal("bad fd argument");
	in = Bopen(0, OREAD);
	
	out = chancreate(sizeof(char*), 0);
	quit = chancreate(sizeof(char*), 0);
	
	for(i = 0; i < argc; i++){
		nread++;
		threadcreate(reader, in[i], 8192);
	}
	proccreate(writer, nil, 8192);
}

void
reader(void *v)
{
	Io *iostr;
	Ioproc *io;
	char *buf, *s, *last;
	int off;
	Channel *out;
	Biobuf *in;
	Str *str;
	iostr = v;
	out = iostr.out;
	in = iostr.in;
	buf = malloc(8192);
	
	io = ioproc();
	off = 0;
	while(n = ioread(io, fd, buf+off, 8192-off) > 0){
		str = malloc(sizeof(Str));
		str->buf = buf;
		s = buf;
		for(;;){
			if(n == 0){
				off = s - last;
				memmove(buff, last, off);
				break;
			}
			while(*s++ != '\n' && n-- > 0)
				str->len++;
			send(out, str);
		}
	}
}


void
writer(void *v)
{
	Alt a[3];
	Str *s;
	
	a[0].op = CHANRCV;
	a[0].c = quit;
	a[0].v = nil;
	a[1].op = CHANRCV;
	a[1].c = out;
	a[1].v = &s;
	a[2].op = CHANEND;
	
	for(;;) switch(alt(a)){
	case 0:
		nread--;
		if(nread <= 0)
			goto done;
		break;
	case 1:
		Bwrite(out, s->buf, s->len);
		free(s);
		break;
	}
done:
	Bflush(out);
}

